﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;
using System.Web.Services;

namespace Framework.WebmasterTool.Articles
{
    public partial class Default : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        public string GridViewSortExpression
        {
            get { return ViewState["GridViewSortExpression"] == null ? "AddedDate" : ViewState["GridViewSortExpression"] as string; }
            set { ViewState["GridViewSortExpression"] = value; }
        }

        public SortDirection GridViewSortOrder
        {
            get { return ViewState["GridViewSortOrder"] == null ? SortDirection.Descending : (SortDirection)ViewState["GridViewSortOrder"]; }
            set { ViewState["GridViewSortOrder"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                LoadCateDDL();
                LoadArticles();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.Article.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void LoadCateDDL()
        {
            string levels = "|---";
            string spaces = "&nbsp;";
            List<udv_Categories> allCate = entity.udv_Categories.ToList();
            List<udv_Categories> cateBannerParent = allCate.Where(ca => ca.ParentID == ConfigPaths.Category_Article_ID).ToList();
            foreach (var item in cateBannerParent)
            {
                ddlCategories.Items.Add(new ListItem(item.Title, item.CateID.ToString()));
                LoadSubCateDDL(ref allCate, item.CateID, ref spaces, levels);
            }
        }

        public void LoadSubCateDDL(ref List<udv_Categories> allCate, int cateParentID, ref string spaces, string levels)
        {
            List<udv_Categories> subCateBanner = allCate.Where(ca => ca.ParentID == cateParentID).ToList();
            foreach (var item in subCateBanner)
            {
                ddlCategories.Items.Add(new ListItem(HttpUtility.HtmlDecode(spaces) + levels + item.Title, item.CateID.ToString()));
                if (entity.udv_Categories.Where(ca => ca.ParentID == item.CateID).ToList().Count > 0)
                {
                    spaces += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    LoadSubCateDDL(ref allCate, item.CateID, ref spaces, levels);
                }
            }
            if (spaces.Length > 6)
                spaces = spaces.Substring(0, spaces.Length - 36);
        }

        public void LoadArticles()
        {
            var articles = entity.udv_Articles.Include("udv_Categories").Select(ar => new { ar.ArticleID, ar.ImageUrl, ar.Title, CateID = ar.udv_Categories.CateID, CateTitle = ar.udv_Categories.Title, ar.AddedDate, ar.IsApproved, ar.DisplayOrder }).ToList();
            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                articles = articles.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                articles = articles.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            grvArticles.DataSource = articles;
            grvArticles.DataBind();
        }

        protected void grvArticles_Sorting(object sender, GridViewSortEventArgs e)
        {
            //Check if the same column is sorted to switch Sort Order  
            if (GridViewSortExpression.Equals(e.SortExpression))
                GridViewSortOrder = GridViewSortOrder.Equals(SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
            else
                GridViewSortOrder = SortDirection.Ascending;
            //save Sort Expression and Sort Order
            GridViewSortExpression = e.SortExpression;
            if (grvArticles.ToolTip == "all")
                LoadArticles();
            else
            {
                SearchArticles();
            }
        }

        protected void grvArticles_DataBinding(object sender, EventArgs e)
        {
            string srcImageASC = Globals.ApplicationPath + "WebmasterTool/Images/ASC.gif";
            string srcImageDESC = Globals.ApplicationPath + "WebmasterTool/Images/DESC.gif";
            foreach (DataControlField column in grvArticles.Columns)
            {
                //Remove Previous Sort Image  
                column.HeaderText = Regex.Replace(column.HeaderText, "<[^>]*>", "", RegexOptions.IgnoreCase);
                if (column.SortExpression.Equals(GridViewSortExpression))
                {
                    //set new sort image  
                    string strSortImageURL = GridViewSortOrder == SortDirection.Descending ?
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageDESC + "' />" :
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageASC + "' />";
                    column.HeaderText = String.Format("{0}{1}", column.HeaderText, strSortImageURL);
                }
            }
        }

        protected void grvArticles_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvArticles.PageIndex = e.NewPageIndex;
            if (grvArticles.ToolTip == "all")
                LoadArticles();
            else
            {
                SearchArticles();
            }
        }

        public void SearchArticles()
        {
            var articles = entity.udv_Articles.Include("udv_Categories").Select(ar => new { ar.ArticleID, ar.ImageUrl, ar.Title, CateID = ar.udv_Categories.CateID, CateTitle = ar.udv_Categories.Title, ar.AddedDate, ar.IsApproved, ar.DisplayOrder }).ToList();
            var searchArticles = entity.udv_Articles.Include("udv_Categories").Where(ar => ar.ArticleID == -1).Select(ar => new { ar.ArticleID, ar.ImageUrl, ar.Title, CateID = ar.udv_Categories.CateID, CateTitle = ar.udv_Categories.Title, ar.AddedDate, ar.IsApproved, ar.DisplayOrder }).ToList();
            if (txtKeyword.Text.Trim() == "" && ddlCategories.SelectedValue != "0")
            {
                int cateID = int.Parse(ddlCategories.SelectedValue);
                List<udv_Categories> allCate = entity.udv_Categories.ToList();
                List<udv_Categories> searchCate = Globals.LoopGetCategories(ref allCate, cateID);
                searchCate.Add(allCate.Where(ca => ca.CateID == cateID).FirstOrDefault());
                foreach (var item in searchCate)
                {
                    searchArticles.AddRange(articles.Where(ar => ar.CateID == item.CateID).ToList());
                }
            }
            else if (txtKeyword.Text.Trim() != "" && ddlCategories.SelectedValue == "0")
            {
                string keywords = Globals.RemoveSign4VietnameseString(txtKeyword.Text.Trim());
                searchArticles = articles.Where(ar => Globals.RemoveSign4VietnameseString(ar.Title.ToLower()).Contains(keywords.ToLower()) || ar.AddedDate.ToString("dd/MM/yyyy").Contains(keywords)).ToList();
            }
            else if (txtKeyword.Text.Trim() != "" && ddlCategories.SelectedValue != "0")
            {
                int cateID = int.Parse(ddlCategories.SelectedValue);
                string keywords = Globals.RemoveSign4VietnameseString(txtKeyword.Text.Trim());
                List<udv_Categories> allCate = entity.udv_Categories.ToList();
                List<udv_Categories> searchCate = Globals.LoopGetCategories(ref allCate, cateID);
                searchCate.Add(allCate.Where(ca => ca.CateID == cateID).FirstOrDefault());
                foreach (var item in searchCate)
                {
                    searchArticles.AddRange(articles.Where(ar => (Globals.RemoveSign4VietnameseString(ar.Title.ToLower()).Contains(keywords.ToLower()) || ar.AddedDate.ToString("dd/MM/yyyy").Contains(keywords)) && ar.CateID == item.CateID).ToList());
                }
            }
            else
                searchArticles = articles;
            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                searchArticles = searchArticles.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                searchArticles = searchArticles.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            grvArticles.DataSource = searchArticles;
            grvArticles.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            grvArticles.PageIndex = 0;
            grvArticles.ToolTip = "search";
            SearchArticles();
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            Response.Redirect("ArticleAdd.aspx");
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in grvArticles.Rows)
            {
                bool isChecked = ((HtmlInputCheckBox)row.FindControl("chkSelect")).Checked;
                if (isChecked)
                {
                    int articleID = int.Parse(((HtmlInputCheckBox)row.FindControl("chkSelect")).Attributes["title"].Trim());
                    udv_Articles articleDelete = entity.udv_Articles.Where(ar => ar.ArticleID == articleID).FirstOrDefault();
                    if (articleDelete != null)
                    {
                        List<udv_ArticleImages> listArticleImage = entity.udv_ArticleImages.Where(ia => ia.udv_Articles.ArticleID == articleDelete.ArticleID).ToList();
                        foreach (var item in listArticleImage)
                        {
                            Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageArticle_Folder_MapPath + item.ImageUrl));
                        }
                        Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageArticle_Folder_MapPath + articleDelete.ImageUrl));
                        //output cache
                        string key = "/ArticleDetails.aspx?ArticleID=" + articleDelete.ArticleID.ToString();
                        Cache.Remove(key);
                        string urlRewriteArticleOld = Globals.CreateUrlRewriteArticle(ref entity, articleDelete.ArticleID, true) + DGSFramework.Globals.GetUrlRewriteExtension();
                        Globals.DeleteROR("~/ror.xml", urlRewriteArticleOld);
                        Globals.DeleteSiteMap("~/sitemap.xml", urlRewriteArticleOld);
                        Globals.DeleteUrlList("~/urllist.txt", urlRewriteArticleOld);
                        //create db log
                        articleDelete.udv_CategoriesReference.Load();
                        CreateDBLog(articleDelete.ArticleID, articleDelete.udv_Categories.CateID, TypeAction.Delete, "Xoá bài viết: " + articleDelete.Title, 
                            articleDelete.Abstract, articleDelete.Body, articleDelete.ReleaseDate != null ? string.Format("{0:dd/MM/yyyy} HH:mm:ss", articleDelete.ReleaseDate) : "", 
                            articleDelete.ReleaseDate != null ? string.Format("{0:dd/MM/yyyy} HH:mm:ss", articleDelete.ReleaseDate) : "",
                            articleDelete.IsApproved.Value.ToString(), articleDelete.StatusID.Value.ToString(), articleDelete.MetaDescription, articleDelete.MetaKeywords);
                        entity.DeleteObject(articleDelete);
                        entity.SaveChanges();
                    }
                }
            }
            //data cache
            Cache.Remove("Article");
            //output cache
            HttpResponse.RemoveOutputCacheItem("/Default.aspx");
            HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
            if (grvArticles.ToolTip == "all")
                LoadArticles();
            else
            {
                SearchArticles();
            }
        }

        [WebMethod]
        public static void UpdateIsApproved(string ArticleID, string IsApproved)
        {
            DGSFrameworkEntities entity = new DGSFrameworkEntities();
            int articleID = int.Parse(ArticleID);
            bool isApproved = IsApproved == "1" ? true : false;

            udv_Articles article = entity.udv_Articles.Where(ar => ar.ArticleID == articleID).FirstOrDefault();
            if (article != null)
            {
                article.IsApproved = isApproved;
                entity.SaveChanges();
            }
        }

        [WebMethod]
        public static void UpdateDisplayOrder(string LstArticleID, string LstDisplayOrder)
        {
            DGSFrameworkEntities entity = new DGSFrameworkEntities();
            var lstArticleID = LstArticleID.Split(',');
            var lstDisplayOrder = LstDisplayOrder.Split(',');

            if (lstArticleID.Count() == lstDisplayOrder.Count())
            {
                for (int i = 0; i < lstArticleID.Count(); i++)
                {
                    int articleID = int.Parse(lstArticleID[i]);
                    int displayOrder = int.Parse(lstDisplayOrder[i]);

                    udv_Articles article = entity.udv_Articles.Where(ar => ar.ArticleID == articleID).FirstOrDefault();
                    if (article != null)
                    {
                        article.DisplayOrder = displayOrder;
                        entity.SaveChanges();
                    }
                }
            }
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}